package study.concurrent.thread.controller;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;

import javax.annotation.PostConstruct;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class PoolController {

    private ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));

    @PostConstruct
    public void init() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            log.info(">>>>>> active_count= {}", pool.getActiveCount());
            log.info(">>>>>> task_count= {}", pool.getTaskCount());
            log.info(">>>>>> completed_task_count= {}", pool.getCompletedTaskCount());
            log.info(">>>>>> largest_pool_size= {}", pool.getLargestPoolSize());
            pool.getQueue().remainingCapacity();

            //
            log.info(">>>>>> queue= {}", pool.getQueue().remainingCapacity());
        }, 0, 5, TimeUnit.SECONDS);
    }

    @RequestMapping("/doTask")
    public Result doTask() {
        pool.submit(() -> {
            log.info(">>>>>> wait for die");
            ThreadUtil.waitForDie();
        });
        return Results.ok();
    }
}
